package cn.edu.buaa.nlsde.grid.DatabaseManage;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.edu.buaa.nlsde.grid.DatabaseConnect.*;
import cn.edu.buaa.nlsde.grid.Structure.*;

public class DataStore
{
	DBPool db=new DBPool(DBInitial.getJndiName());
	GridConfigManage gridConfig=new GridConfigManage(db);
	ClusterConfigManage clusterConfig=new ClusterConfigManage(db);
	HostConfigManage hostConfig=new HostConfigManage(db);
	GlobalMapping map=new GlobalMapping(db);
	
	MetricSystemManage system=new MetricSystemManage(db);
	MetricCpuManage cpu=new MetricCpuManage(db);
	MetricMemoryManage memory=new MetricMemoryManage(db);
	MetricProcessManage process=new MetricProcessManage(db);
	MetricLoadManage load=new MetricLoadManage(db);
	MetricPktsManage pkts=new MetricPktsManage(db);
	MetricDiskManage disk=new MetricDiskManage(db);
	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	long datetime=System.currentTimeMillis();
	Date date=new Date(datetime);
	String collectTime=sdf.format(date);
	
	public void storeData(Grid grid)
	{
		
		List<Cluster> clusters=grid.getClusters();
		int GridID=0;
		gridConfig.addRecord(GridID, grid);
		
		for(int i=0;i<clusters.size();i++)
		{
			Cluster cluster=(Cluster)clusters.get(i);
			int ClusterID=GridID*10+i;
			
			if(ClusterID!=-1)
			{
				clusterConfig.addRecord(ClusterID,cluster);
				List<Host> hosts=cluster.getHosts();
				
				for(int j=0;j<hosts.size();j++)
				{
					Host host=(Host)hosts.get(j);
					int HostID=ClusterID*10+j;
					hostConfig.addRecord(HostID,host);
				
					if(HostID!=-1)
					{
						map.buildMap(GridID,ClusterID,HostID);
						
						system.addRecord(HostID,host,collectTime);
						cpu.addRecord(HostID,host,collectTime);
						memory.addRecord(HostID,host,collectTime);
						process.addRecord(HostID,host,collectTime);
						load.addRecord(HostID,host,collectTime);
						pkts.addRecord(HostID,host,collectTime);
						disk.addRecord(HostID,host,collectTime);
					}
				}
			}
		}
	}
	
	public void close() throws SQLException
	{
		db.close();
	}
}
